package controllers;

import play.Logger;

import play.mvc.*;

import com.fasterxml.jackson.databind.JsonNode; 

import models.Info;
import views.html.*;
import models.*;
import models.ManagerOfClients;

@org.springframework.stereotype.Controller
public class Application {

    public static Result index() {
        return play.mvc.Controller.ok(index.render());
    }
    
    public static Result chatRoom(String username) {
        if(username == null || username.trim().equals("")) {
        	play.mvc.Controller.flash("error", "Please choose a valid username.");
            return play.mvc.Controller.redirect(routes.Application.index());
        }
        System.out.println("tutja");
        return play.mvc.Controller.ok(chatRoom.render(username));
    }

    public static Result chatRoomJs(String username) {
    	System.out.println("juz tu");
        return play.mvc.Controller.ok(views.js.chatRoom.render(username));
    }
    
    /**
     * Handle the chat websocket.
     */
    public static WebSocket<JsonNode> chat(final String username) {
        return new WebSocket<JsonNode>() {
            
            // Called when the Websocket Handshake is done.
            public void onReady(WebSocket.In<JsonNode> in, WebSocket.Out<JsonNode> out){
                
            	ManagerOfClients.notifyAll(new Info("I've got a WebSocket", username));
            	
                // Join the chat room.
                try {                	
                	ManagerOfClients.addNewClient(username, in, out);
                	System.out.println("socet utowrzono");
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        };
}
}
